package com.collection.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.collection.common.base.FilterModel;
import com.collection.dto.FilterDto;


/**
 * 构造HQL辅助类
 * @author 冯勇
 *
 */
public class HQLHelpUtil {
	
	private static List<String> filedNames;
	
	private static List<Object> filedValues;

	/**
	 * 根据过滤条件重组HQL语句
	 * @param filter 过滤条件
	 * @return HQL语句
	 */
	public static String createHQL(Map<FilterDto, Object> filter) {
		StringBuffer sb = new StringBuffer();
		Set<FilterDto> filterKeys = filter.keySet();
		filedNames = new ArrayList<String>();
		filedValues = new ArrayList<Object>();
		int index = 0;
		for(FilterDto filterDto:filterKeys) {
			String fieldName = filterDto.getFiledName();
			Object fieldValue = filter.get(filterDto);
			switch(filterDto.getModel()) {
				case EQ : 
					sb.append(fieldName).append(" = ? ");
					break;
				case NE :
					sb.append(fieldName).append(" <> ? ");
					break;
				case LT :
					sb.append(fieldName).append(" < ? ");
					break;
				case GT :
					sb.append(fieldName).append(" > ? ");
					break;
				case LE :
					sb.append(fieldName).append(" <= ? ");
					break;
				case GE :
					sb.append(fieldName).append(" >= ? ");
					break;
				case LIKE :
					sb.append(fieldName).append(" like ? ");
					break;
			}
			
			filedNames.add(fieldName);
			
			if(filterDto.getModel().equals(FilterModel.LIKE)) {
				filedValues.add("%"+fieldValue+"%");
			} else {
				filedValues.add(fieldValue);
			}
			
			if(sb.length() > 0 && index < filterKeys.size()-1) {
				sb.append(" and ");
			}
			index ++;
		}
		return sb.toString();
	}

	public static List<String> getFiledNames() {
		return filedNames;
	}

	public static List<Object> getFiledValues() {
		return filedValues;
	}
}
